// Copyright (c) 2022 Presto Labs Pte. Ltd.
// Author: hgpark

#include <gflags/gflags.h>
#include <spdlog/async.h>
#include <spdlog/sinks/basic_file_sink.h>
#include <spdlog/sinks/rotating_file_sink.h>
#include <spdlog/spdlog.h>

#include <ctime>
#include <sstream>

#include "coin2/base/time.h"
#include "coin2/strategy/rmm_strat/genoi_strategy.h"

DEFINE_string(driver, "", "driver config");
DEFINE_string(config, "", "strategy config");
DEFINE_string(key_filepath, "", "key filepath");

int main(int argc, char* argv[]) {
  gflags::ParseCommandLineFlags(&argc, &argv, true);
  std::string strat_name = std::experimental::filesystem::path(FLAGS_driver);
  strat_name = strat_name.substr(strat_name.find_last_of("/"), strat_name.length());
  strat_name = strat_name.substr(1, strat_name.find_last_of(".") - 1);
  google::InitGoogleLogging(strat_name.c_str());

  /*
  auto current_time = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
  std::tm tm = *std::localtime(&current_time);
  std::stringstream log_filename_suffix;
  log_filename_suffix << std::put_time(&tm, "%Y%m%d_%H%M%S");
  */
  // split log files every 1 GiB / at most 5 files
  auto rotating_async_logger = spdlog::rotating_logger_mt<spdlog::async_factory>(
      "async_file_logger",
      fmt::format("{}/data/genoi_log/{}", std::getenv("HOME"), strat_name),
      1048576 * 1024,
      4);
  spdlog::set_default_logger(rotating_async_logger);
  // flush every 5 sec
  spdlog::flush_every(std::chrono::seconds(5));
  spdlog::set_pattern("%Y%m%d.%H%M%S.%f [%s:%!:%#] %v");

  auto path = std::experimental::filesystem::path(FLAGS_driver);
  coin2::app::DriverConfig app_config;
  app_config.MergeFrom(coin2::base::config::DriverConfigFromJson(path));
  /*
  (*app_config.mutable_strategy()).set_strategy_name(strat_name);
  (*app_config.mutable_order()->mutable_exchanges())["Prex"].mutable_connection_config()
    ->set_key_filepath(FLAGS_key_filepath);
  */
  SPDLOG_INFO("App config: {}", app_config.DebugString());

  coin2::strategy::rmm_strat::GenOiStrategy strategy(FLAGS_config);
  coin2::app::Driver driver(app_config, &strategy);
  // strategy.SetMainIoc(driver.live_executor()->MainIoc());
  driver.RegisterCleanupHandler();
  driver.Run();
  return 0;
}

